﻿using System;
using System.IO;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Autorent.Desktop.Main.Converters
{
    /// <summary>
    /// Convert Byte array to image as BitmapImage class
    /// </summary>
    public class ByteArrayToImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            BitmapImage image = null;

            if (value != null)
            {
                byte[] photoData = value as byte[];

                MemoryStream mem = new MemoryStream(photoData);

                mem.Write(photoData, 0, photoData.Length);

                mem.Seek(0, SeekOrigin.Begin);
                
                image = new BitmapImage();
                image.BeginInit();
                image.DecodePixelWidth = 100;
                image.DecodePixelHeight = 100;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.StreamSource = mem;
                image.EndInit();
            }

            return image;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return null;
        }
    }
}
